<template>
  <div class="add-edit-container">
    <el-form
      ref="spuForm"
      :model="spuForm"
      label-width="80px"
      :rules="spuFormRules"
    >
      <el-form-item label="SPU名称" prop="spuName" required>
        <el-input v-model="spuForm.spuName" />
      </el-form-item>
      <el-form-item label="品牌" prop="tmId" required>
        <el-select v-model="spuForm.tmId" placeholder="请选择">
          <el-option
            v-for="item in brandsList"
            :key="item.id"
            :label="item.tmName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input v-model="spuForm.description" />
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="imageList"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="sellAttr"
          :placeholder="`还有${saleAttrList.length}未选择`"
        >
          <el-option
            v-for="item in saleAttrList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          class="add-attr"
          :disabled="!sellAttr"
          @click="onAddAttr"
          >添加销售属性</el-button
        >
      </el-form-item>
      <el-table
        style="width: 100%; margin-bottom: 20px"
        :data="spuForm.spuSaleAttrList"
      >
        <el-table-column type="index" label="序号" width="width" />
        <el-table-column label="属性名" prop="saleAttrName" />
        <el-table-column label="属性名称列表">
          <template #default="{ row }">
            <el-tag
              v-for="(tag, index) in row.spuSaleAttrValueList"
              :key="tag.id"
              closable
              :disable-transitions="false"
              @close="handleClose(row, index)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.inputVisible"
              ref="saveTagInput"
              v-model="row.inputValue"
              v-focus
              class="input-new-tag"
              size="small"
              @keyup.enter.native="handleInputConfirm(row)"
              @blur="handleInputConfirm(row)"
            />
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(row)"
              >添加</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="prop"
          label="操作"
        >
          <template #default="{ $index }">
            <el-popconfirm title="确定删除吗？" @confirm="onDelete($index)">
              <el-button
                slot="reference"
                type="danger"
                size="mini"
                icon="el-icon-delete"
              />
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-form-item>
        <el-button type="primary" @click="onSave">保存</el-button>
        <el-button @click="$emit('cancel')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getItem, removeItem } from "utils/storage";
export default {
  name: "AddEditSpu",
  components: {},
  props: {
    category3Id: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      brandsList: [],
      // 销售属性
      sellAttr: "",
      spuForm: {
        category3Id: "",
        description: "",
        id: "",
        spuImageList: null,
        spuName: "",
        spuSaleAttrList: [],
        tmId: "",
      },
      baseSaleAttrRes: [],
      imageList: [],
      attrTableList: [],
      spuFormRules: {
        spuName: [
          { required: true, message: "请输入SPU名称", trigger: "blur" },
        ],
        tmId: [{ required: true, message: "请选择品牌", trigger: "blur" }],
      },
    };
  },
  computed: {
    spuRow() {
      return getItem("spuRow");
    },
    // 销售属性
    saleAttrList() {
      return this.baseSaleAttrRes.reduce((acc, val) => {
        const { name } = val;
        const flag = this.spuForm.spuSaleAttrList.some(
          (val) => val.saleAttrName === name
        );
        console.log(flag);
        if (!flag) {
          acc.push(val);
        }
        return acc;
      }, []);
    },
  },
  watch: {},
  created() {
    // 有spuRow说明是点编辑spu进来的
    this.spuRow ? this.getPageData("edit") : this.getPageData("add");
  },
  mounted() {},
  beforeDestroy() {
    removeItem("spuRow");
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    async getPageData(type) {
      // 考虑到4个请求互不影响,所以并行发送出去
      if (type === "edit") {
        const [
          { data: tradeMarkRes },
          { data: baseSaleAttrRes },
          { data: spuInfoRes },
          { data: spuImagesRes },
        ] = await Promise.all([
          this.$api.spu.getTradeMarkList(),
          this.$api.spu.getBaseSaleAttr(),
          this.$api.spu.getSpuInfoById(this.spuRow.id),
          this.$api.spu.getSpuImage(this.spuRow.id),
        ]);
        console.log(spuInfoRes);
        this.handleRes(tradeMarkRes, baseSaleAttrRes, spuInfoRes, spuImagesRes);
      } else {
        const [{ data: tradeMarkRes }, { data: baseSaleAttrRes }] =
          await Promise.all([
            this.$api.spu.getTradeMarkList(),
            this.$api.spu.getBaseSaleAttr(),
          ]);
        this.handleRes(tradeMarkRes, baseSaleAttrRes);
      }
    },
    // 处理得到的结果
    handleRes(
      tradeMarkRes,
      baseSaleAttrRes,
      spuInfoRes = {},
      spuImagesRes = null
    ) {
      if (Object.keys(spuInfoRes).length > 0) {
        spuInfoRes.spuSaleAttrList.forEach((val) => {
          val.inputValue = "";
          val.inputVisible = false;
        });
        this.spuForm = spuInfoRes;
      }
      if (spuImagesRes) {
        this.imageList = spuImagesRes.map((val) => {
          return {
            url: val.imgUrl,
            name: val.imgName,
          };
        });
      }
      this.brandsList = tradeMarkRes;
      this.baseSaleAttrRes = baseSaleAttrRes;
    },
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1);
    },

    showInput(row) {
      row.inputVisible = true;
    },

    handleInputConfirm(row) {
      if (row.inputValue) {
        const obj = {
          saleAttrValueName: row.inputValue,
          baseSaleAttrId: row.baseSaleAttrId,
        };
        if (!row.spuSaleAttrValueList) {
          this.$set(row, "spuSaleAttrValueList", []);
        }
        row.spuSaleAttrValueList.push(obj);
      }
      row.inputVisible = false;
      row.inputValue = "";
    },
    onAddAttr() {
      const { sellAttr } = this;
      let obj = this.baseSaleAttrRes.find((val) => val.id === sellAttr);
      obj = JSON.parse(
        JSON.stringify(obj)
          .replace("name", "saleAttrName")
          .replace("id", "baseSaleAttrId")
      );
      obj.inputVisible = false;
      obj.inputValue = "";
      this.spuForm.spuSaleAttrList.push(obj);
      this.sellAttr = "";
    },
    // 删除某行
    onDelete(index) {
      this.spuForm.spuSaleAttrList.splice(index, 1);
    },
    handleSuccess(res, file) {
      const obj = {
        url: file.response.data,
        name: file.name,
      };
      this.imageList.push(obj);
    },
    onSave() {
      this.$refs.spuForm.validate(async (valid) => {
        if (valid) {
          this.spuForm.spuImageList = this.imageList.map((val) => {
            return {
              imgUrl: val.url,
              imgName: val.name,
            };
          });
          if (this.spuForm.category3Id === "") {
            this.spuForm.category3Id = this.category3Id;
          }
          const res = await this.$api.spu.addOrUpdateSpu(this.spuForm);
          if (res.code === 200) {
            const message = this.spuForm.id ? "修改成功" : "添加成功";
            this.$message.success(message);
            this.$emit("edit-success");
          }
        }
      });
    },
  },
};
</script>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
<style scoped lang="scss">
.add-attr {
  margin-left: 20px;
}
</style>
